//
//  XYCallDetailVC.m
//  Zhihuijinfu
//
//  Created by XY Lv on 17/3/26.
//  Copyright © 2017年 王笛. All rights reserved.
//

#import "XYCallDetailVC.h"
#import "XYCallDetailCell.h"
#import "XYCallDetailItem.h"
#import "XYCallDetailHeaderView.h"
#import "XYLocalAlertView.h"
#import "XYKeyboardView.h"
#import "IQKeyboardManager.h"
#import "XYCallDetailFooterView.h"
#import "LGPhoto.h"
@interface XYCallDetailVC ()<UITableViewDelegate,UITableViewDataSource,XYLocalAlertViewDelegate,XYKeyboardViewDelegate,UITextViewDelegate,LGPhotoPickerBrowserViewControllerDataSource,LGPhotoPickerBrowserViewControllerDelegate,XYFooterDelegate>
{
    UITableView * _xyTableView;
    XYCallDetailItem * _xyDataItem;
    XYCallDetailHeaderView * _xyHeaderView;
    XYLocalAlertView * _xyLocalView;
    UILabel *          _xyTimeLabel;
    XYKeyboardView  *  _xyKeyboardView;
    NSString        *  _xyTimeStamp;
    XYCallDetailFooterView * _xyFooterView;
    LGShowImageType _xyShowType;
    NSMutableArray  *  _xyLGPhotoMArr;

}
@end

@implementation XYCallDetailVC

- (void)viewWillAppear:(BOOL)animated{
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar  = NO;

}

- (void)viewWillDisappear:(BOOL)animated{
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar  = YES;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    if([self.xyBusinessDetailItem.type isEqualToString:@"2"]){
        [self loadNavItemWithLeftAction:@selector(xyClickNavLeftBtn) leftBtnImage:@"icon_back" leftBtnSelImage:@"icon_back" title:@"面访签到" rihgtAction:@selector(clickNavRightBtn) rightBtnImage:nil rightBtnSelImage:nil];

            [self xyLayoutLocalView];
           [self xyLayoutFooterView];

        

    }else if([self.xyBusinessDetailItem.type isEqualToString:@"1"]){
        [self loadNavItemWithLeftAction:@selector(xyClickNavLeftBtn) leftBtnImage:@"icon_back" leftBtnSelImage:@"icon_back" title:@"电话回访" rihgtAction:@selector(clickNavRightBtn) rightBtnImage:nil rightBtnSelImage:nil];

        [self xyLayoutTimeLabel];

    }
    [self xyLayoutHeaderView];
    [self xyLayoutTableView];
    [self xyLayoutKeyboardView];
    
    [self xyRequestGetCallBackDetail];

}

- (void)xyLayoutLocalView{
    _xyLocalView = [[XYLocalAlertView alloc]initWithFrame:CGRectMake(0, 0, WDScreenW, xyLocalAlertViewH)];
    _xyLocalView.delegate = self;
    [self.view addSubview:_xyLocalView];
    _xyLocalView.xyLocalStr = @"北京市南门外大街123号";
}

- (void)xyLayoutTimeLabel{
    _xyTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, WDScreenW, xyLocalAlertViewH)];
    _xyTimeLabel.backgroundColor = [UIColor colorWithRed:0.94 green:0.95 blue:0.95 alpha:1.00];
    _xyTimeLabel.textAlignment = NSTextAlignmentCenter;
    _xyTimeLabel.textColor = xyPublisTimeTextColor;
    _xyTimeLabel.font = xyPublisTimeFont;
    [self.view addSubview:_xyTimeLabel];
    
}

- (void)xyLayoutTableView{
    
    _xyTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,xyLocalAlertViewH,WDScreenW, WDScreenH - xyKeyboardViewH - 64 - xyLocalAlertViewH) style:UITableViewStylePlain];
    [self.view addSubview:_xyTableView];
    _xyTableView.dataSource = self;
    _xyTableView.delegate = self;
    _xyTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _xyTableView.tableHeaderView = _xyHeaderView;
    _xyTableView.tableFooterView = _xyFooterView;
    
    [self xyLayoutRefreshTableView];
}

- (void)xyLayoutHeaderView{
    _xyHeaderView = [[XYCallDetailHeaderView alloc]initWithFrame:CGRectMake(0, 0, WDScreenW, xy(200))];
    _xyHeaderView.xyBusinessCellItem = self.xyBusinessDetailItem;

    
}

- (void)xyLayoutFooterView{
    _xyFooterView = [[XYCallDetailFooterView alloc]initWithFrame:CGRectMake(0, 0, WDScreenW, xy(100))];
    _xyFooterView.delegate = self;
    
}

- (void)xyLayoutKeyboardView{
    _xyKeyboardView = [[XYKeyboardView alloc]initWithFrame:CGRectMake(0,WDScreenH - xyKeyboardViewH - 64, WDScreenW, xyKeyboardViewH)];
    _xyKeyboardView.backgroundColor = [UIColor redColor];
    _xyKeyboardView.delegate = self;
    _xyKeyboardView.xyTextView.delegate = self;
    _xyKeyboardView.xyTextView.placeholder = @"点击输入评论";
    _xyKeyboardView.backgroundColor = xyLightGrayColor;
    _xyKeyboardView.layer.shadowColor = [UIColor colorWithRed:0.91 green:0.92 blue:0.92 alpha:1.00].CGColor;
    _xyKeyboardView.layer.shadowOffset =  CGSizeMake(1, 1);
    _xyKeyboardView.layer.borderWidth = 1;
    _xyKeyboardView.layer.borderColor = [UIColor colorWithRed:0.91 green:0.92 blue:0.92 alpha:1.00].CGColor;
    [self.view addSubview:_xyKeyboardView];
}

- (void)xyRefreshHeaderView{
    _xyHeaderView.xyDetailItem = _xyDataItem;
    _xyHeaderView.frame = CGRectMake(0, 0, WDScreenW, _xyHeaderView.xyH);
    _xyTimeLabel.text = _xyDataItem.create_time;
}

- (void)xyRefreshFooterView{
    _xyFooterView.xyPhotosMArr = [NSMutableArray arrayWithArray:self.xyBusinessDetailItem.file_data];
//    _xyFooterView.frame = CGRectMake(0, 0, WDScreenW,_xyFooterView.xyFooterH);
//    _xyTableView.tableFooterView = _xyFooterView;
//    [_xyFooterView.xyPhotosCollectionView reloadData];

    [self xyPreareLGPhotosMArr];
}

- (void)xyPreareLGPhotosMArr{
    _xyLGPhotoMArr = [NSMutableArray array];
    
        for(NSDictionary * dic in self.xyBusinessDetailItem.file_data){
            LGPhotoPickerBrowserPhoto *photo = [[LGPhotoPickerBrowserPhoto alloc] init];
            photo.photoURL = [NSURL URLWithString:[dic objectForKey:xyPhoto_url]];
            [_xyLGPhotoMArr addObject:photo];
            
        }
    
    
    
    
}

- (NSArray *)xySubviewsFrameArr{
    
    if(!_xySubviewsFrameArr||_xySubviewsFrameArr.count != _xyDataItem.chat_data.count){
        NSMutableArray * modelsMArr = [[NSMutableArray alloc]init];
        for(XYCallDetailCommentItem * commentItem in _xyDataItem.chat_data){
            XYCallDetailFrame * frame = [[XYCallDetailFrame alloc]init];
            [frame setCommentItem:commentItem];
            [modelsMArr addObject:frame];
        }
        _xySubviewsFrameArr = [modelsMArr copy];
    }
    return _xySubviewsFrameArr;
}

- (void)xyPushPhotoBroswerWithStyle:(LGShowImageType)style withIndexPath:(NSIndexPath*)indexPath{
    LGPhotoPickerBrowserViewController *BroswerVC = [[LGPhotoPickerBrowserViewController alloc] init];
    BroswerVC.delegate = self;
    BroswerVC.dataSource = self;
    BroswerVC.showType = style;
    _xyShowType = style;
    NSInteger  num = indexPath.section*2+indexPath.row;
    
    BroswerVC.currentIndexPath = [NSIndexPath indexPathForRow:num inSection:0];
    
    [self presentViewController:BroswerVC animated:YES completion:nil];
}


//代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"多少:%ld",_xyDataItem.chat_data.count);
    return _xyDataItem.chat_data.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * cellId = @"xyCell";
    
    XYCallDetailCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(!cell){
        cell= [[XYCallDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    cell.detailFrame = [self.xySubviewsFrameArr objectAtIndex:indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    XYCallDetailFrame * frame = [self.xySubviewsFrameArr objectAtIndex:indexPath.row];
    return frame.xyCellH;
}

- (void)xyLocalAlertViewTap:(id)sender{
    NSLog(@"xyLocalAlertViewTap");
}

- (void)textViewDidChange:(XYTextView *)textView{
    if (textView.hasText) { // textView.text.length
        textView.placeholder = @"";
        
    } else {
        textView.placeholder = @"点击输入评论";
        
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSString * str = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    if(str.length >1000){
        [_xyKeyboardView.xyTextView endEditing:YES];
        [self showAlertWithMessage:@"最多1000字"];
    }else{
        
    }
    return YES;
}

- (void)xySendTextBtnClick:(UIButton *)sender withObject:(id)object{
    NSLog(@"发送:%@",_xyKeyboardView.xyTextView.text);
    [self xyRequestSendComment];
//    _xyKeyboardView.xyTextView.text = nil;
}

- (void)xyPhotoTapToBrowserWithIndexPath:(NSIndexPath *)indexPath{
    _xyShowType = LGShowImageTypeImageURL;
    NSInteger  num = indexPath.section*2+indexPath.row;
    if(_xyLGPhotoMArr.count >num){
        [self xyPushPhotoBroswerWithStyle:_xyShowType withIndexPath:indexPath];

    }
}

- (NSInteger)photoBrowser:(LGPhotoPickerBrowserViewController *)photoBrowser numberOfItemsInSection:(NSUInteger)section{
    if (_xyShowType == LGShowImageTypeImageBroswer) {
    return _xyLGPhotoMArr.count;
} else if (_xyShowType == LGShowImageTypeImageURL) {
    return _xyLGPhotoMArr.count;
} else {
    NSLog(@"非法数据源");
    return 0;
}
}

- (id<LGPhotoPickerBrowserPhoto>)photoBrowser:(LGPhotoPickerBrowserViewController *)pickerBrowser photoAtIndexPath:(NSIndexPath *)indexPath{
    if (_xyShowType == LGShowImageTypeImageBroswer) {
        return [_xyLGPhotoMArr objectAtIndex:indexPath.item];
        
    } else if (_xyShowType == LGShowImageTypeImageURL) {
        return [_xyLGPhotoMArr objectAtIndex:indexPath.item];
    } else {
        NSLog(@"非法数据源");
        return nil;
    }
}

//点击事件
- (void)xyClickNavLeftBtn{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)clickNavRightBtn{
    
}

//请求
- (void)xyRequestGetCallBackDetail{
    NSDictionary * paraDic = @{@"follow_id":self.xyFollow_id};
    
    [WDHTTPMethod xy_requestPostJsonWithUrl:xyUrl_getCallBackDetail withItemClass:[XYCallDetailItem class] parameters:paraDic isAddCookie:YES success:^(id responseObject) {
        NSLog(@"获取跟进记录详情:%@",responseObject);
       _xyDataItem = responseObject;
        NSLog(@"1:%@",_xyDataItem.error_code);
        if([_xyDataItem.error_code isEqualToString:@"0"]){
            _xyTimeStamp = _xyDataItem.time_stamp;
        }
        for(XYCallDetailCommentItem * commentItem in _xyDataItem.chat_data) {
            NSLog(@"评论:%@",commentItem.content);
        }
        [self xyRefreshHeaderView];
        [self xyRefreshFooterView];
        [_xyTableView reloadData];
    } fail:^{
        
    }];
}

- (void)xyRequestSendComment{
    NSDictionary * paraDic = @{@"follow_id":self.xyFollow_id,@"content":_xyKeyboardView.xyTextView.text,@"time_stamp":_xyTimeStamp};
    
    [WDHTTPMethod xy_requestPostJsonWithUrl:xyUrl_sendCallBackComment withItemClass:[XYBaseItem class] parameters:paraDic isAddCookie:YES success:^(id responseObject) {
        XYBaseItem * baseItem = responseObject;
        if([baseItem.error_code isEqualToString:@"0"]){
            _xyTimeStamp = baseItem.time_stamp;
            [SVProgressHUD showSuccessWithStatus:@"评论成功"];
            _xyKeyboardView.xyTextView.text = nil;
            [self xyRequestGetCallBackDetail];
        }else{
            [SVProgressHUD showErrorWithStatus:@"评论失败!"];
        }
    } fail:^{
        
    }];
}

- (void)xyLayoutRefreshTableView{
    _xyTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self xyRequestGetCallBackDetail];
        [_xyTableView.mj_header endRefreshing];
    }];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
